package com.example.encrypition;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.widget.TextView;

import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

//非对称加密
//加密和解密两套密码
//为什么加密和解密不同密码？
//费马大定律：勾股定理：3*3+4*4=5*5;
public class RSAActivity extends AppCompatActivity {

    private PrivateKey privateKey;
    private PublicKey publicKey;
    private TextView showKeys;
    private String string;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rsa);
        initView();
    }

    private void initView() {
        showKeys = ((TextView) findViewById(R.id.showKeys));
    }


    //生成公钥私钥
    public void generate(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //1、获取公钥和私钥生成的对象
                    KeyPairGenerator generator=KeyPairGenerator.getInstance("RSA");

                    //2、初始化,指定密码的长度bit
                    generator.initialize(1024*3);

                    //3、获取公钥和私钥
                    KeyPair keyPair = generator.generateKeyPair();

                    //3.1获取私钥(非常重要，要保存好，私钥如果丢了，就找不回来了)
                    privateKey = keyPair.getPrivate();

                    //3.2获取公钥(公钥丢了的话可以通过私钥找回)
                    publicKey = keyPair.getPublic();

                    //私钥的具体数据，私钥字节数据，保存该数据，文件中，sp
                    //！！！必须进行Base64转换
                    byte[] privateKeyEncoded = privateKey.getEncoded();

                    byte[] publicKeyEncoded = publicKey.getEncoded();


                    //对公钥私钥进行Base64编码
                    final byte[] privateEncode = Base64.encode(privateKeyEncoded, Base64.DEFAULT);

                    final byte[] publicEncode = Base64.encode(publicKeyEncoded, Base64.DEFAULT);

                    //显示到文本框
                    showKeys.post(new Runnable() {
                        @Override
                        public void run() {
                            showKeys.setText("私钥是："+"\n"+new String(privateEncode)
                            +"\n"+"公钥是："+"\n"+new String(publicEncode));
                        }
                    });
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //使用公钥私钥进行加密界面
    public void encrypt(View view) {
        //使用私钥去加密，使用公钥进行解密
        /*
        举例：
        阿里巴巴----传给千锋（其他公司，达内），传文件
        文件加密，私钥加密文件，传给千锋
        千锋持有公钥，公钥进行解密
        */
        String check="1";
        switch (view.getId()) {
            case R.id.rsaEncrypt://加密
                try {
                    //1、获取加密引擎
                    Cipher cipher=Cipher.getInstance("RSA");

                    //2、初始化
                    if (privateKey!=null){
                        cipher.init(Cipher.DECRYPT_MODE,privateKey);
                    }

                    //加密
                    byte[] doFinal = cipher.doFinal(check.getBytes());

                    byte[] base64Encode = Base64.encode(doFinal, Base64.DEFAULT);

                    //显示数据
                    string = new String(base64Encode);
                    showKeys.setText("RSA加密的数据是："+ string);

                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (NoSuchPaddingException e) {
                    e.printStackTrace();
                } catch (InvalidKeyException e) {
                    e.printStackTrace();
                } catch (BadPaddingException e) {
                    e.printStackTrace();
                } catch (IllegalBlockSizeException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.rsaDecrypt://解密
                try {
                    //1、获取解密引擎
                    Cipher cipher=Cipher.getInstance("RSA");

                    //2、初始化
                    if (publicKey!=null){
                        cipher.init(Cipher.ENCRYPT_MODE,publicKey);
                    }

                    //解密
                    byte[] base64Encode = Base64.decode(string.getBytes(), Base64.DEFAULT);

                    byte[] doFinal = cipher.doFinal(base64Encode);


                    //显示数据
                    showKeys.setText("RSA解密的数据是："+new String(doFinal));

                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (NoSuchPaddingException e) {
                    e.printStackTrace();
                } catch (InvalidKeyException e) {
                    e.printStackTrace();
                } catch (BadPaddingException e) {
                    e.printStackTrace();
                } catch (IllegalBlockSizeException e) {
                    e.printStackTrace();
                }
                break;
        }
    }
}
